<template>
    <!-- 库位码管理主页 -->
    <div class="depot">
        <div class="depot_left" v-loading="treeLoading">
            <div class="depot_left_top">
                <img src="@/assets/images/depot/icon_kuweijiagou.png" alt="">
                <h2>库位架构</h2>
            </div>
            <el-button class="depot_left_button" type="primary" round plain :icon="Plus"
                @click="addFloorClick">新增楼层</el-button>
            <div class="depot_left_tree">
                <el-tree :data="treeData" :props="{ children: 'child', label: 'dictLabel' }" highlight-current
                    default-expand-all :expand-on-click-node="false" :check-on-click-node="true"
                    @node-click="treeNodeClick" />
            </div>
        </div>
        <div class="depot_right">
            <div class="depot_right_form">
                <el-form ref="ruleFormRef" :inline="true" :model="queryParams" class="demo-form-inline">
                    <el-form-item label="货架类型" prop="shelvesType">
                        <el-select v-model="queryParams.shelvesType" clearable placeholder="请选择货架类型" filterable
                            style="width: 200px;">
                            <el-option v-for="dict in hm_stock_shelves_type" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="货架码" prop="alias">
                        <el-input v-model="queryParams.alias" clearable placeholder="请输入货架码" @keyup.enter="getList"
                            style="width: 200px;" />
                    </el-form-item>
                    <el-form-item>
                        <el-button class="form_button" type="primary" round @click="getList">查询</el-button>
                        <el-button class="form_button" type="primary" round plain @click="resetForm()">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="depot_right_operate">
                <div>
                    <el-button class="operate_button" type="primary" :disabled="!treeValue.dictValue" plain
                        @click="addLocationClick">新增</el-button>
                    <el-button class="operate_button" type="primary" plain :disabled="!ckeckArr.length"
                        @click="batchClick('start')">启用</el-button>
                    <el-button class="operate_button" type="danger" plain :disabled="!ckeckArr.length"
                        @click="batchClick('forbidden')">禁用</el-button>
                    <el-button class="operate_button" type="danger" :disabled="!ckeckArr.length"
                        @click="batchClick('delete')">删除</el-button>
                </div>
                <el-button class="operate_print" type="primary" round :disabled="!ckeckArr.length"
                    @click="batchClick('print')">打印</el-button>
            </div>
            <el-table ref="multipleTableRef" :data="tableData" v-loading="tableLoading" style="width: 100%"
                @selection-change="tableCkeckChange">
                <el-table-column type="selection" width="55" />
                <el-table-column property="shelvesType" label="货架类型" show-overflow-tooltip />
                <el-table-column property="floor" label="楼层" show-overflow-tooltip />
                <!-- <el-table-column property="area" label="区域号" show-overflow-tooltip /> -->
                <el-table-column property="locationRow" label="排号" show-overflow-tooltip />
                <el-table-column property="shelves" label="货架号" show-overflow-tooltip />
                <el-table-column property="layer" label="层号" show-overflow-tooltip />
                <el-table-column property="name" label="货架码" show-overflow-tooltip />
                <el-table-column property="status" label="库位状态" show-overflow-tooltip>
                    <template #default="scope">
                        {{ scope.row.status == 1 ? '启用' : '禁用' }}
                    </template>
                </el-table-column>
                <el-table-column property="address" label="操作" width="250">
                    <template #default="scope">
                        <el-button v-if="scope.row.status == 2" type="primary" link
                            @click="tableOperate('start', scope.row)">启用</el-button>
                        <el-button type="danger" v-if="scope.row.status == 1" link
                            @click="tableOperate('forbidden', scope.row)">禁用</el-button>
                        <el-button type="primary" link @click="tableOperate('print', scope.row)">打印</el-button>
                        <el-button type="danger" link @click="tableOperate('delete', scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableTotal > 0" :total="tableTotal" :page-sizes="[50, 100, 200, 500]"
                v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </div>
        <addFloor ref="addFloorRef" @getTreeData="getTreeData" />
        <reminder ref="reminderRef" />
        <addLocation ref="addLocationRef" @getList="getList" />
        <print ref="printRef" />
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { locationList, stockLocationEnable, stockLocationDisable, stockLocationDel } from '@/api/depot/index'
import { listData } from '@/api/system/dict/data/index'
import addFloor from './components/addFloor.vue'
import reminder from './components/reminder.vue'
import addLocation from './components/addLocation.vue'
import print from './components/print.vue'
import { debounce } from 'lodash'

const { proxy } = getCurrentInstance() as any;

const { hm_stock_shelves_type } = toRefs(proxy?.useDict('hm_stock_shelves_type'));

const treeLoading = ref<boolean>(false)
const tableLoading = ref<boolean>(false)
// 新增楼层ref
const addFloorRef = ref()
// 新增库位ref
const addLocationRef = ref()
// 提示消息对话框ref
const reminderRef = ref()
// 表单ref
const ruleFormRef = ref()
// 打印ref
const printRef = ref()
// 表格绑定数据
const tableData = ref<Array<any>>([])
const tableTotal = ref(0)
// 表格复选框选择
const ckeckArr = ref<Array<any>>([])
// 左侧树数据
const treeData = ref<Array<any>>([])
// 左侧树value
const treeValue = ref<any>({})

// 查询表格列表的参数
const queryParams = ref({
    pageNum: 1,
    pageSize: 200,
    shelvesType: "",    // 货架类型
    alias: '',         // 库位号
    name: '',
})
// 获取树数据
const getTreeData = async () => {
    const { rows = [] } = await listData({
        pageNum: 1, 
        pageSize: 20, 
        dictType: 'hm_stock_location_floor', 
        dictName: '',
        dictLabel: ''
    })
    treeData.value = rows
}
// 获取列表数据
const getList = async () => {
    tableLoading.value = true
    try {
        const { rows = [], total = 0 } = await locationList(queryParams.value)
        tableData.value = rows
        tableLoading.value = false
        tableTotal.value = total
    } catch (error) {
        tableLoading.value = false
    }
}

// 新增楼层
const addFloorClick = debounce(() => {
    addFloorRef.value.isShow = true
}, 200)

// 新增库位
const addLocationClick = debounce(() => {
    addLocationRef.value.int(treeValue.value)
}, 200)

// 批量操作
const batchClick = debounce(async (type: string) => {
    // start:启用     forbidden：禁用    delete：删除    print：打印
    const arr: Array<string | number> = []
    ckeckArr.value.forEach((item: any) => {
        arr.push(item.locationId)
    })
    const params = {
        locationId: arr
    }
    tableLoading.value = true
    if (type === 'start') {
        try {
            const { code = 200, msg } = await stockLocationEnable(params)
            tableLoading.value = false
            if (code == 200) {
                ElMessage({
                    message: '批量启用成功',
                    type: 'success',
                })
            } else {
                ElMessage({
                    message: msg,
                    type: 'error',
                })
            }
        } catch (error) {
            tableLoading.value = false
        }
    } else if (type === 'forbidden') {
        try {
            const { code = 200, msg } = await stockLocationDisable(params)
            tableLoading.value = false
            if (code == 200) {
                ElMessage({
                    message: '批量禁用成功',
                    type: 'success',
                })
            } else {
                reminderRef.value.int('禁用')
            }
        } catch (error) {
            tableLoading.value = false
        }

    } else if (type === 'delete') {
        try {
            const { code = 200, msg } = await stockLocationDel(params)
            tableLoading.value = false
            if (code == 200) {
                ElMessage({
                    message: '批量删除成功',
                    type: 'success',
                })
            } else {
                reminderRef.value.int('删除')
            }
        } catch (error) {
            tableLoading.value = false
        }
    } else {
        const data = setPrintData(ckeckArr.value)
        printRef.value.int(data)
    }
    getList()
}, 200)
// 表格操作中的点击
const tableOperate = debounce(async (type: string, row: any) => {
    tableLoading.value = true
    // start:启用     forbidden：禁用    delete：删除    print：打印
    if (type === 'start') {
        try {
            const { code = 200 } = await stockLocationEnable({ locationId: [row.locationId] })
            tableLoading.value = false
            ElMessage({
                message: '启用成功',
                type: 'success',
            })
        } catch (error) {
            tableLoading.value = false
        }
    } else if (type === 'forbidden') {
        try {
            const { code = 200 } = await stockLocationDisable({ locationId: [row.locationId] })
            tableLoading.value = false
            if (code == 200) {
                ElMessage({
                    message: '禁用成功',
                    type: 'success',
                })
            } else {
                reminderRef.value.int('禁用')
            }
        } catch (error) {
            tableLoading.value = false
        }
    } else if (type === 'delete') {
        try {
            const { code = 200 } = await stockLocationDel({ locationId: [row.locationId] })
            tableLoading.value = false
            if (code == 200) {
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
            } else {
                reminderRef.value.int('删除')
            }
        } catch (error) {
            tableLoading.value = false
        }

    } else {
        const data = setPrintData([row])
        printRef.value.int(data)
    }
    getList()
}, 200)

// 树节点点击
const treeNodeClick = debounce((row: any, data: any) => {
    queryParams.value.name = row.dictValue
    queryParams.value.pageNum = 1
    treeValue.value = row
    getList()
}, 200)

// 重置
const resetForm = debounce(() => {
    ruleFormRef.value.resetFields()
    getList()
}, 200)

// table复选框change事件
const tableCkeckChange = debounce((val: Array<any>) => {
    ckeckArr.value = val
}, 200)

// 处理打印数据
const setPrintData = (arr: Array<any>) => {
    const barcodePrintData: Array<any> = []
    arr.forEach(item => {
        const obj = {
            InitDrawingBoardParam: {
                width: 70,
                height: 80,
                rotate: 0,
                path: "ZT001.ttf",
                verticalShift: 0,
                HorizontalShift: 0,
            },
            elements: [{
                type: "barCode",
                json: {
                    x: 10.0,
                    y: 27.5,
                    width: 50,
                    height: 25,
                    value: item.name,
                    codeType: 20,
                    rotate: 0,
                    fontSize: 7.0,
                    textHeight: 7.0,
                    textPosition: 0,
                }
            }]
        }
        barcodePrintData.push(obj)
    })
    return barcodePrintData
}

onMounted(() => {
    getTreeData()
    getList()
})

</script>
<style lang="scss" scoped>
@import url(./style/index.scss);
</style>